#define echoPin 13 // Echo Pin

#define trigPin 12 // Trigger Pin

#define relay 11

int maximumRange = 500; // Maximum range needed

int minimumRange = 0; // Minimum range needed

long duration, distance; // Duration used to calculate distance

int openValue=60;
int closeValue=80;

bool isOn=false;


void setup() {

Serial.begin (9600);

pinMode(trigPin, OUTPUT);

pinMode(relay, OUTPUT);

pinMode(echoPin, INPUT);

}

void loop() {


digitalWrite(trigPin, LOW);

delayMicroseconds(2);

digitalWrite(trigPin, HIGH);

delayMicroseconds(10);

digitalWrite(trigPin, LOW);

duration = pulseIn(echoPin, HIGH);

//Calculate the distance (in cm) based on the speed of sound.

distance = duration/58.2;

if (distance >= maximumRange || distance <= minimumRange){

Serial.println("-1");

}

else {

Serial.print("distance:");
Serial.print(distance);
Serial.println("cm");
if(distance>=openValue-5&&distance<=openValue+5&&!isOn)
{
  Serial.println("1");
  digitalWrite(relay,HIGH);
  isOn=true;
  delay(1000);
}
if(distance>=closeValue-5&&distance<=closeValue+5&&isOn)
{
  isOn=false;
  digitalWrite(relay,LOW);
  Serial.println("0");
  delay(1000);
}  
}
delay(100);

}
